package com.cloudinnov.intercept;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.cloudinnov.controller.api.BaseController;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.PropertiesUtils;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author guochao
 * @date 2016年2月26日下午5:56:52
 * @email chaoguo@cloudinnov.com
 * @remark 登陆拦截器
 * @version
 */

public class UserLoginInterceptor extends BaseController implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(UserLoginInterceptor.class);

	@Autowired
	private JedisPool jedisPool;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		if ("IE".equals(request.getParameter("type"))) {
			response.addHeader("XDomainRequestAllowed", "1");
		}
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_NULL);

		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			String token = request.getParameter("token");
			String loginFlag = redisClient.get("login:" + token + ":loginFlag");
			if (loginFlag != null && loginFlag.equals("success")) {
				
				String loginName = redisClient.get("login:" + token + ":loginName");
				request.setAttribute(LOGIN_NAME, loginName);
				String userName = redisClient.get("login:" + token + ":name");
				request.setAttribute(USER_NAME, userName);
				String oemCode = redisClient.get("login:" + token + ":oemCode");
				request.setAttribute(OEM_CODE, oemCode);
				String integratorCode = redisClient.get("login:" + token + ":integratorCode");
				request.setAttribute(INTEGRATOR_CODE, integratorCode);
				String userCode = redisClient.get("login:" + token + ":code");
				request.setAttribute(USER_CODE, userCode);
				String userLogo = redisClient.get("login:" + userCode + ":logo");
				request.setAttribute(USER_LOGO, userLogo);
				String companyCode = redisClient.get("login:" + token + ":companyCode");
				request.setAttribute(COM_CODE, companyCode);
				String userType = redisClient.get("login:" + token + ":type");
				request.setAttribute(USER_TYPE, userType);
				// 设置失效时间
				int outOfServiceTime = Integer.valueOf(PropertiesUtils.findPropertiesKey("tokenTimeOut"));
				redisClient.setex("login:" + token + ":code", outOfServiceTime, userCode);
				redisClient.setex("login:" + token + ":loginName", outOfServiceTime, loginName);
				redisClient.setex("login:" + token + ":name", outOfServiceTime, userName);
				redisClient.setex("login:" + token + ":companyCode", outOfServiceTime, companyCode);
				if (oemCode != null) {
					redisClient.setex("login:" + token + ":oemCode", outOfServiceTime, oemCode);
				}
				if (integratorCode != null) {
					redisClient.setex("login:" + token + ":integratorCode", outOfServiceTime, integratorCode);
				}
				redisClient.setex("login:" + token + ":type", outOfServiceTime, userType);
				redisClient.setex("login:" + token + ":loginFlag", outOfServiceTime, "success");
				if(redisClient.get("app:login:"+token)!=null){
					request.setAttribute(LOGIN_TYPE, CommonUtils.LOGIN_TYPE_APP);
				}else{
					request.setAttribute(LOGIN_TYPE, CommonUtils.LOGIN_TYPE_WEB);
				}
				return true;
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", LOGIN_ERROR_TOKEN);
			map.put("msg", CommonUtils.getLanguage(request));
			response.getWriter().println(mapper.writeValueAsString(map));
		} catch (Exception e) {
			logger.error("登录拦截器异常 \r {}" , e);
		} finally {
			jedisPool.returnResource(redisClient);
		}
		return false;

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
